<template>
  <div class="card-container">
    <Tabs v-model:activeKey="activeKey" type="card">
      <TabPane key="1" tab="短信消息模板">
        <BasicTable @register="registerTableInformation">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <TableAction
                :actions="[
                  {
                    label: record.topOp ? '取消置顶' : '置顶',
                    tooltip: record.topOp ? '取消置顶' : '置顶',
                    onClick: handleSmsTop.bind(null, record),
                  },
                  {
                    label: '编辑',
                    tooltip: '编辑',
                    onClick: handleAddInformation.bind(null, 'informationEdit', record),
                  },
                  {
                    label: '删除',
                    tooltip: '删除',
                    onClick: handleDelInformation.bind(null, record),
                  },
                ]"
            /></template>
          </template>
          <template #toolbar>
            <a-button type="primary" @click="handleAddInformation('informationAdd', {})"
              >新建模板</a-button
            >
          </template>
        </BasicTable>
      </TabPane>
      <TabPane key="2" tab="公众号消息模板">
        <BasicTable @register="registerTableOfficial">
          <template #bodyCell="{ column, text, record }">
            <template v-if="['typeName', 'sceneName'].includes(column.dataIndex)">
              <div>
                <a-input
                  v-if="editableData[record.id] && column.dataIndex === 'sceneName'"
                  v-model:value="editableData[record.id][column.dataIndex]"
                  style="margin: -5px 0"
                />
                <Cascader
                  v-else-if="editableData[record.id] && column.dataIndex === 'typeName'"
                  :options="cascaderOptions"
                  :fieldNames="{
                    label: 'name',
                    value: 'id',
                    children: 'nodeList',
                  }"
                  v-model:value="editableData[record.id][column.dataIndex]"
                />
                <template v-else>
                  {{ text }}
                </template>
              </div>
            </template>
            <template v-else-if="column.dataIndex === 'action'">
              <div class="editable-row-operations">
                <span v-if="editableData[record.id]">
                  <TypographyLink @click="save(record.id)">保存</TypographyLink>
                  <Popconfirm title="确认取消编辑?" @confirm="cancel(record.id)">
                    <a>取消</a>
                  </Popconfirm>
                </span>
                <span v-else>
                  <a @click="edit(record.id)">编辑</a>
                </span>
                <span>
                  <a @click="handlewechatTop(record)">{{ record.topOp ? '取消置顶' : '置顶' }}</a>
                </span>
              </div>
            </template>
            <!-- <template v-if="column.key === 'action'">
              <TableAction
                :actions="[
                  {
                    label: '编辑',
                    tooltip: '编辑',
                    onClick: handleAddOfficial.bind(null, record),
                  },
                ]"
            /></template> -->
          </template>
          <template #displayContent="{ column, record }">
            <div style="white-space: break-spaces; text-align: left">{{
              record.displayContent
            }}</div>
          </template>
        </BasicTable>
      </TabPane>
    </Tabs>
  </div>
</template>

<script lang="ts" setup>
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { Modal, Tabs, TabPane, TypographyLink, Popconfirm, Cascader } from 'ant-design-vue';
  import {
    SmsDel,
    SmsList,
    TypeTreeDownList,
    WechatTemplateList,
    WechatTemplateListByTypeId,
    WechatTemplateModify,
    TypeById,
    smsTemplateTop,
    wechatTemplateTop,
  } from '@/api/message/template';
  import { getBasicColumns as getBasicColumnsInformation } from './tableDataInformation';
  import { getBasicColumns as getBasicColumnsOfficial } from './tableDataOfficial';
  import Dictionary from '@/utils/dictionary';
  import { UnwrapRef, onMounted, reactive, ref } from 'vue';
  import { router } from '@/router';
  import { ISmsListResult, IWechatTemplateListResult } from '@/api/message/template/type';
  import { useMessage } from '@/hooks/web/useMessage';
  import { cloneDeep } from 'lodash-es';

  const activeKey = ref('1');
  const { createMessage } = useMessage();
  const dicts = Dictionary.getLocalMulti(['smsType', 'smsAuditStatus']);

  //短信消息模板
  const [registerTableInformation, { reload: reloadInformation, getForm }] = useTable({
    title: '',
    api: SmsList,
    columns: getBasicColumnsInformation(),
    rowKey: 'id',
    formConfig: {
      labelWidth: 100,
      schemas: [
        {
          field: `keyword`,
          label: `模板名称`,
          component: 'Input',
          colProps: {
            span: 5,
          },
        },
        {
          field: `smsType`,
          label: `短信类型`,
          component: 'Select',
          componentProps: {
            fieldNames: { label: 'dictLabel', value: 'dictValue' },
            options: dicts.smsType,
          },
          colProps: {
            span: 4,
          },
        },
        {
          field: `smsTemplateTypeId`,
          label: `消息类型`,
          component: 'Cascader',
          colProps: {
            span: 5,
          },
        },
        {
          field: `auditStatus`,
          label: `模板状态`,
          component: 'Select',
          componentProps: {
            fieldNames: { label: 'dictLabel', value: 'dictValue' },
            options: dicts.smsAuditStatus,
          },
          colProps: {
            span: 4,
          },
        },
      ],
    },
    useSearchForm: true,
    showTableSetting: false,
    tableSetting: { fullScreen: true },
    showIndexColumn: true,
    clickToRowSelect: false,
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
    },
    beforeFetch: (data) => {
      let { smsTemplateTypeId } = data;
      return {
        ...data,
        smsTemplateTypeId:
          smsTemplateTypeId &&
          smsTemplateTypeId.length &&
          smsTemplateTypeId[smsTemplateTypeId.length - 1],
      };
    },
    afterFetch: (data: ISmsListResult[]) => {
      return data.map((item) => {
        return {
          ...item,
          smsType: dicts.smsType.find((f) => f.dictValue === item.smsType)?.dictLabel,
          auditStatus: dicts.smsAuditStatus.find((f) => f.dictValue === item.auditStatus)
            ?.dictLabel,
        };
      });
    },
  });

  onMounted(async () => {
    let form = getForm();
    let list = await TypeTreeDownList();
    form.updateSchema({
      field: 'smsTemplateTypeId',
      componentProps: {
        options: list,
        fieldNames: {
          label: 'name',
          value: 'id',
          children: 'nodeList',
        },
      },
    });
  });

  function handleAddInformation(type: 'informationAdd' | 'informationEdit', row: any) {
    console.log(type, row);
    router.push({
      path: `/message/${type}`,
      query: { id: row.id },
    });
  }

  const handleSmsTop = async (row: ISmsListResult) => {
    await smsTemplateTop({ id: row.id, topOp: !row.topOp });
    createMessage.success('操作成功！');
    reloadInformation();
  };

  const handlewechatTop = async (row: IWechatTemplateListResult) => {
    await wechatTemplateTop({ id: row.id, topOp: !row.topOp });
    createMessage.success('操作成功！');
    reload();
  };

  function handleDelInformation(row: ISmsListResult) {
    Modal.confirm({
      title: '提示',
      content: '该操作将删除该模板',
      onOk: async () => {
        await SmsDel(row.id);
        createMessage.success('删除成功！');
        reloadInformation();
      },
    });
  }

  //公众号消息模板
  const dataSource = ref<IWechatTemplateListResult[]>([]);
  const editableData: UnwrapRef<Record<string, IWechatTemplateListResult>> = reactive({});

  const edit = (key: number) => {
    editableData[key] = cloneDeep(dataSource.value.filter((item) => key === item.id)[0]);
  };
  const save = async (key: number) => {
    let item = editableData[key];
    if (Array.isArray(item.typeName)) {
      let typeId = item.typeName[item.typeName.length - 1];
      let res = await TypeById(typeId);
      item.typeId = typeId;
      item.typeName = res.name;
    }
    await WechatTemplateModify({
      id: item.id,
      sceneName: item.sceneName,
      typeId: item.typeId,
      typeName: item.typeName,
    });
    createMessage.success('保存成功！');
    reload();
    delete editableData[key];
  };
  const cancel = (key: number) => {
    delete editableData[key];
  };

  const cascaderOptions = ref([]);

  const getTypeTreeDownList = async () => {
    let res = await TypeTreeDownList();
    cascaderOptions.value = res;
  };
  getTypeTreeDownList();

  const [registerTableOfficial, { reload }] = useTable({
    title: '',
    api: WechatTemplateList,
    columns: getBasicColumnsOfficial(),
    rowKey: 'id',
    // formConfig: {
    //   labelWidth: 100,
    //   schemas: [
    //     {
    //       field: `typeId`,
    //       label: `消息类型`,
    //       component: 'ApiSelect',
    //       colProps: {
    //         span: 4,
    //       },
    //       componentProps: {
    //         api: TypeTreeDownList,
    //         labelField: 'name',
    //         valueField: 'id',
    //         placeholder: '请选择消息类型',
    //       },
    //     },
    //   ],
    // },
    // useSearchForm: false,
    showTableSetting: false,
    tableSetting: { fullScreen: true },
    showIndexColumn: true,
    clickToRowSelect: false,
    actionColumn: {
      width: 150,
      title: '操作',
      dataIndex: 'action',
    },
    afterFetch: (data: IWechatTemplateListResult[]) => {
      dataSource.value = data;
    },
  });
</script>

<style lang="less">
  .card-container {
    margin: 16px;
  }

  .card-container > .ant-tabs-card > .ant-tabs-nav {
    margin: 0;
  }

  .card-container p {
    margin: 0;
  }

  .card-container > .ant-tabs-card .ant-tabs-content {
    height: 100vh;
  }
  .card-container > .ant-tabs-card .ant-tabs-content > .ant-tabs-tabpane {
    background: #fff;
  }
  .card-container > .ant-tabs-card > .ant-tabs-nav::before {
    display: none;
  }
  .card-container > .ant-tabs-card .ant-tabs-tab,
  [data-theme='compact'] .card-container > .ant-tabs-card .ant-tabs-tab {
    background: transparent;
    border-color: transparent;
  }
  .card-container > .ant-tabs-card .ant-tabs-tab-active,
  [data-theme='compact'] .card-container > .ant-tabs-card .ant-tabs-tab-active {
    background: #fff;
    border-color: #fff;
  }
  #components-tabs-demo-card-top .code-box-demo {
    padding: 24px;
    overflow: hidden;
    background: #f5f5f5;
  }
  [data-theme='compact'] .card-container > .ant-tabs-card .ant-tabs-content {
    height: 120px;
    margin-top: -8px;
  }
  [data-theme='dark'] .card-container > .ant-tabs-card .ant-tabs-tab {
    background: transparent;
    border-color: transparent;
  }
  [data-theme='dark'] #components-tabs-demo-card-top .code-box-demo {
    background: #000;
  }
  [data-theme='dark'] .card-container > .ant-tabs-card .ant-tabs-content > .ant-tabs-tabpane {
    background: #141414;
  }
  [data-theme='dark'] .card-container > .ant-tabs-card .ant-tabs-tab-active {
    background: #141414;
    border-color: #141414;
  }

  .editable-row-operations a {
    margin-right: 8px;
  }
</style>
